<!--
 * @Author: 李小晴 2689279066@qq.com
 * @Date: 2023-06-14 16:04:00
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-11-20 16:35:01
 * @FilePath: \sys\src\views\SmartPasture\Raise\Feed\components\Edit.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="ts">
import { reactive, ref, watch, PropType } from 'vue'
import { ElTree, ElMessage } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { required } from '@/utils/formRules'
import { spForageFormulaSeeApi, spForageFormulaListApi } from '@/api/sp/food'
import { spFeedSeeApi } from '@/api/sp/feed'
import { spEnclosureListApi } from '@/api/fa/enclosure'
import { zcPastureListApi } from '@/api/fa/pasture'
import { ucDeptListApi } from '@/api/uc/dept'
import { ucOrgDeptUserListApi } from '@/api/fa/user'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()

const newDeptTreeData = ref<any[]>([])
const newUserData = ref<any[]>([])
const myDeptList: any = wsCache.get('myDeptList')
const myUserList: any = ref(wsCache.get('myUserList'))
const e_id = ref(0) //主要用来给每个行添加一个序号，删除的时候好定位
const data = ref<any>({})
const treeRef = ref<ComponentRef<typeof ElTree>>()

data.value.checkedAll = null
data.value.selectData = null
data.value.noSelectData = null

const rules = reactive({
  org_id: [required],
  type: [required],
  forage_formula_id: [required],
  number: [required],
  feed_time: [required],
  threshold: [required],
  pasture_org_id: [required]
})

const props = defineProps({
  id: {
    type: String,
    default: null
  },
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const getSee = async () => {
  if (props.id) {
    const res = await spFeedSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      res.data.number = res.data.number ? Number(res.data.number) : 0
      data.value = res.data
      e_id.value = data.value?.detailed.length
      let aaa = data.value?.detailed
      aaa.forEach((element, index) => {
        element.e_id = index + 1
      })
      data.value.detailed = aaa
      await DeptList(data.value.pasture_org_id)
      await getAllEnclosure(data.value.pasture_org_id)
      data.value.selectData = data.value.select_json
        ? JSON.parse(data.value.select_json).selected
        : ''
      await methodsForm.setValues(data.value.selectData)
      treeRef.value!.setCheckedKeys(data.value.selectData, false)
      treeRef.value!.getCheckedNodes(false, false).forEach((element) => {
        total_weight = Number(element.all_weight) + Number(total_weight)
      })
      await methodsForm.setValues(data.value)
    }
    await methodsForm.setValues(data.value)
  } else {
    data.value.detailed = []
    await methodsForm.setValues(data.value)
  }
}
let total_weight = 0

const treeCheck = async (a, b) => {
  let formData = await methodsForm.getFormData()
  console.log(a)
  data.value.number = 0
  total_weight = 0
  data.value.selectData = b.checkedKeys
  if (b.checkedNodes.length > 0) {
    b.checkedNodes.forEach((element) => {
      data.value.number = data.value.number + Number(element.this_asset_count)
      total_weight = Number(element.all_weight) + Number(total_weight)
      // total_weight = element.all_weight + total_weight
      data.value.detailed.forEach((element1) => {
        element1.weight = (
          0.0001 *
          Number(element1.ratio) *
          Number(formData?.threshold) *
          Number(total_weight)
        ).toFixed(2)
      })
    })
  } else {
    data.value.detailed.forEach((element1) => {
      element1.weight = 0
    })
  }
  methodsForm.setValues(data.value)
}
const forageFormulaSee = async (val) => {
  const res = await spForageFormulaSeeApi({ id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    await res.data.detailed.forEach((element1) => {
      element1.weight = 0
    })
    data.value.detailed = await res.data.detailed
  }
}
const onFormula = async (value, b) => {
  data.value.forage_formula_id = value
  data.value.threshold = b.threshold
  await forageFormulaSee(value)
}
// 管理员用户列表
const myUserListChange = async (value) => {
  myUserList.value = []
  data.value.admin_dept_id = value
  data.value.admin_user_id = ''
  data.value.admin_user_name = ''
  const props = {
    org_id: wsCache.get('userInfo').default_org_id,
    dept_id: value
  }
  const res = await ucOrgDeptUserListApi(props)
    .catch(() => {})
    .finally(() => {})
  if (res) {
    myUserList.value = res.data
  }
}
const DeptList = async (value) => {
  data.value.pasture_org_id = value
  const res = await ucDeptListApi({ org_id: value })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newDeptTreeData.value = res.data
  }
  if (props.id) {
    await UserList(data.value.pasture_dept_id)
  }
}
const stateChangeAdminUser = async (value) => {
  data.value.admin_user_id = value
}
const stateChangeUser = async (value) => {
  data.value.pasture_user_id = value
}
const UserList = async (value) => {
  data.value.pasture_dept_id = value
  data.value.pasture_user_id = ''
  await methodsForm.setValues(data.value)
  newUserData.value = []
  const props = {
    org_id: data.value.pasture_org_id,
    dept_id: data.value.pasture_dept_id
  }
  const res = await ucOrgDeptUserListApi({ ...props })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    newUserData.value = res.data
  }
}

const onCustomer = async (value) => {
  await getAllEnclosure(value)
  data.value.checkedAll = false
  data.value.selectData = []
  data.value.noSelectData = []
  data.value.number = 0
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    newDeptTreeData.value = []
    data.value.pasture_dept_id = ''
    data.value.pasture_user_id = ''
    await DeptList(value)
  }
  await methodsForm.setValues(data.value)
}

const spForageFormulaList = async (val) => {
  val.pasture_org_id = data.value.pasture_org_id
  return spForageFormulaListApi(val)
}

const onThreshold = async (val) => {
  data.value.threshold = val
  if (val) {
    data.value.detailed.forEach((element1) => {
      element1.weight = (
        0.0001 *
        Number(element1.ratio) *
        Number(val) *
        Number(total_weight)
      ).toFixed(2)
    })
  } else {
    ElMessage.warning('阀值不能为空')
  }
}

const schemaAdd = reactive<FormSchema[]>([
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '牧场用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'forage_formula_id',
    label: '饲料配方',
    component: 'DialogRefer',
    componentProps: {
      getListApi: spForageFormulaList,
      response: { count: 'count', data: 'data' },
      title: '选择饲料配方（双击选择）',
      nameField: 'forage_formula_name',
      relNameField: 'name',
      valueField: 'id',
      crudSchemas: [{ field: 'name', label: '名称', search: { show: true } }],
      modelName: data.value.forage_formula_name,
      onChange: onFormula
    }
  },
  {
    field: 'threshold',
    label: '喂养阈值',
    component: 'Input',
    componentProps: {
      onChange: onThreshold
    }
  },
  {
    field: 'feed_time',
    component: 'DatePicker',
    label: '投喂时间',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'number',
    label: '喂养数',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '请选择资产'
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input'
  }
])
const schemaEdit = reactive<FormSchema[]>([
  {
    field: 'admin_dept_id',
    label: '管理部门',
    component: 'TreeSelect',
    componentProps: {
      data: myDeptList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: myUserListChange
    }
  },
  {
    field: 'admin_user_id',
    label: '管理用户',
    component: 'TreeSelect',
    componentProps: {
      data: myUserList,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeAdminUser
    }
  },
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListApi,
      response: { count: 'count', data: 'data' },
      title: '选择牧场（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [{ field: 'org_name', label: '牧场名称', search: { show: true } }],
      modelName: data.value.pasture_org_name,
      onChange: onCustomer
    }
  },
  {
    field: 'pasture_dept_id',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      data: newDeptTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      onChange: UserList
    }
  },
  {
    field: 'pasture_user_id',
    label: '所属用户',
    component: 'TreeSelect',
    componentProps: {
      data: newUserData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'user_id',
      props: {
        children: 'children',
        label: 'nickname'
      },
      onChange: stateChangeUser
    }
  },
  {
    field: 'forage_formula_id',
    label: '饲料配方',
    component: 'DialogRefer',
    componentProps: {
      getListApi: spForageFormulaList,
      response: { count: 'count', data: 'data' },
      title: '选择饲料配方（双击选择）',
      nameField: 'forage_formula_name',
      relNameField: 'name',
      valueField: 'id',
      crudSchemas: [{ field: 'name', label: '名称', search: { show: true } }],
      modelName: data.value.forage_formula_name,
      onChange: onFormula
    }
  },
  {
    field: 'threshold',
    label: '喂养阈值',
    component: 'Input',
    componentProps: {
      onChange: onThreshold
    }
  },
  {
    field: 'feed_time',
    component: 'DatePicker',
    label: '投喂时间',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss'
    }
  },
  {
    field: 'number',
    label: '喂养数',
    component: 'Input',
    componentProps: {
      disabled: true,
      placeholder: '请选择资产'
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input'
  }
])
const {
  register: registerForm,
  methods: methodsForm,
  elFormRef
} = useForm({
  schema: props.currentRow ? schemaEdit : schemaAdd
})

const getFormData = async () => {
  let formData = await methodsForm.getFormData()
  return {
    ...formData
  }
}

defineExpose({
  data,
  getFormData,
  elFormRef
})

const feed_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 20
  },
  {
    field: 'forage_name',
    label: '饲料名称',
    width: 90
  },
  {
    field: 'ratio',
    label: '比例（%）'
  },
  {
    field: 'weight',
    label: '总喂养重量',
    width: 180
  }
])

const getAllEnclosure = async (val) => {
  let res = await spEnclosureListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value.detailedEnclosure = res.data
  }
}

watch(
  () => data,
  (value) => {
    if (!value) return
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methodsForm
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => data,
  (value) => {
    if (!value) return
    methodsForm.setValues(data.value)
  },
  {
    deep: true,
    immediate: true
  }
)

const init = async () => {
  await getSee()
}
init()

/****************************** 初始化 end ******************************/
</script>
<template>
  <div>
    <ContentWrap title="主数据">
      <Form :rules="rules" @register="registerForm" :data="data" />
    </ContentWrap>
    <ContentWrap title="选择栏位" v-if="data.pasture_org_id">
      <ElTree
        ref="treeRef"
        :data="data.detailedEnclosure"
        :props="{ children: 'children', label: 'name' }"
        :expand-on-click-node="false"
        node-key="id"
        show-checkbox
        default-expand-all
        check-strictly
        @check="treeCheck"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span v-if="data.all_weight">{{
              node.label +
              '   存栏数:' +
              data.this_asset_count +
              '   总重量:' +
              data.all_weight +
              'kg'
            }}</span>
            <span v-else>{{ node.label + '   存栏数：' + data.this_asset_count }}</span>
          </span>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap title="饲料配方明细" v-if="data.forage_formula_id">
      <Table :columns="feed_columns" :data="data.detailed" :selection="false" :border="true">
        <!-- <template #realWeight="{ row }">
          <ElInput v-model="row.realWeight" />
        </template> -->
      </Table>
    </ContentWrap>
  </div>
</template>
